package com.grantheath.erebus.model.loaders 
{
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.Event;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	import com.grantheath.erebus.model.helpers.ErebusLoadEvent;
	import com.grantheath.erebus.model.interfaces.IErebusAssetLoader;
	import com.grantheath.erebus.model.interfaces.IErebusAssetNode;

	/**
	 * @author grantheath
	 */
	public class ErebusTextAssetLoader extends URLLoader implements IErebusAssetLoader 
	{
		private var _assetNode : IErebusAssetNode;
		
		public function ErebusTextAssetLoader()
		{
			super();
			dataFormat = URLLoaderDataFormat.TEXT;
			addEventListener(Event.OPEN, dispatchOpenEvent);
			addEventListener(Event.COMPLETE, dispatchCompleteEvent);
			addEventListener(ProgressEvent.PROGRESS, dispatchProgressEvent);
			addEventListener(IOErrorEvent.IO_ERROR, dispatchErrorEvent);
		}
		
		public function loadAsset(assetNode : IErebusAssetNode) : void
		{
			_assetNode = assetNode;
			load(new URLRequest(assetNode.assetSrc));
		}
	
		//EVENT HANDELERS
		public function dispatchOpenEvent(event : Event) : void
		{
			dispatchEvent(new ErebusLoadEvent(ErebusLoadEvent.LOAD_OPEN));
		}
		
		public function dispatchCompleteEvent(event : Event) : void
		{
			dispatchEvent(new ErebusLoadEvent(ErebusLoadEvent.LOAD_COMPLETE));
		}
		
		public function dispatchProgressEvent(event : Event) : void
		{
			dispatchEvent(new ErebusLoadEvent(ErebusLoadEvent.LOAD_PROGRESS));
		}

		public function dispatchErrorEvent(event : Event) : void
		{
			dispatchEvent(new ErebusLoadEvent(ErebusLoadEvent.LOAD_ERROR));
		}
		
		//GETTERS AND SETTERS
		public function get loadedBytesCount() : uint
		{
			return bytesLoaded;
		}

		public function get totalBytesCount() : uint
		{
			return bytesTotal;
		}

		public function get percentLoaded() : Number
		{
			return bytesLoaded/bytesTotal;
		}

		public function get assetNode() : IErebusAssetNode
		{
			return _assetNode;
		}

		public function set assetNode(assetNode : IErebusAssetNode) : void
		{
			_assetNode = assetNode;
		}

		public function get loadedAsset() : Object
		{
			return data as String;
		}
	}
}
